package org.os.framework.crypto.algorithm;

import cn.hutool.core.lang.Assert;
import lombok.SneakyThrows;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.util.encoders.Hex;
import org.os.framework.crypto.model.AbstractHash;

/**
 * HMacSHA256
 *
 * @author 魏祖潇
 */
public class HmacSha256 extends AbstractHash {

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private String password;
        private String salt;

        public Builder password(String password) {
            this.password = password;
            return this;
        }

        public Builder salt(String salt) {
            this.salt = salt;
            return this;
        }

        public HmacSha256 build() {
            return new HmacSha256(this.password, this.salt);
        }

    }

    private final String HmacSHA256 = "HmacSHA256";

    /**
     * 密码
     */
    private byte[] password;

    /**
     * 盐值
     */
    private String salt;

    public HmacSha256(String password, String salt) {
        Assert.notNull(password, "请输入密码");
        Assert.isTrue(password.getBytes().length > 0, "密码长度至少1bit");
        this.password = password.getBytes();
        this.salt = salt == null ? "" : salt;
    }

    @SneakyThrows
    @Override
    public String digest(String s) {
        String data = s + salt;
        Mac mac = Mac.getInstance(HmacSHA256);
        SecretKeySpec secretKey = new SecretKeySpec(password, HmacSHA256);
        mac.init(secretKey);
        return Hex.toHexString(mac.doFinal(data.getBytes()));
    }

}
